import bge
import time, functools
import mathutils
import math
import os
#while(totaltime <2):

LAPSE = 0.025
BList = []
keyboard = bge.logic.keyboard
run = True
totaltime = 0
initFlag = True
frames = 0
scene = bge.logic.getCurrentScene()
sceneObjectCount = len(scene.objects)
sceneObjects = []
sceneObjects += scene.objects
lasttime = time.time()

BehaviourFolder = "Nodes"
Behaviours = []
for (path, dirs, files) in os.walk("./" +BehaviourFolder):
    for file in files:
        if(file[-2:] == "py" and file != "__init__.py"):
            Behaviours.append(file[:-3])
            print("from " + BehaviourFolder +"." + file[:-3] + " import main as "+ file[:-3])
            exec("from " + BehaviourFolder +"." + file[:-3] + " import main as "+ file[:-3])
#exec(imptext)
for object in scene.objects:
    for behaviour in Behaviours:
        if(behaviour in object.getPropertyNames()):
            print("BList.append("+behaviour+"(object))")
            exec("BList.append("+behaviour+"(object))")

def main():
    global LAPSE
    global BList
    global keyboard
    global run
    global totaltime
    global initFlag
    global frames
    global lasttime
    global Behaviours
    global sceneObjectCount
    global scene
    global sceneObjects
    
    if(sceneObjectCount != len(scene.objects)):
        for object in scene.objects:
            if(object not in sceneObjects):
                for behaviour in Behaviours:
                    if(behaviour in object.getPropertyNames()):
                        exec("BList.append("+behaviour+"(object))")
        sceneObjectCount = len(scene.objects)
        sceneObjects = []
        sceneObjects += scene.objects
    tim = time.time()
    for bhvr in BList:
        action = bhvr.mainLoop()
        if(action == True):
            BList.remove(bhvr)
        elif(action is not None):
            for portal in action:
                for bhvr in BList:
                    try:
                        if portal[0] in bhvr.Nodes:
                            eval("bhvr.Nodes[\""+portal[0]+"\"].start(\""+ portal[1] +"\",bhvr)")
                    except AttributeError:
                        print("Error de atributo")
                        
    #print(GameLogic.NextFrame())
    frames= frames+1
    totaltime = totaltime + (tim-lasttime)
    print(totaltime)
    #print(object.worldOrientation)
    #Player.worldOrientation = Player.worldOrientation * mathutils.Matrix.Rotation(math.radians(10), 3, 'Z')
    #MoveObject(Player, 0,1,0,True) 
    #RotateObject(Player,0,0,.1,True)  
    #RotateObject(Player,0,0,0,True) 
    #print(Player.worldTransform)
    #print(Player.localTransform)

    extime=time.time()
    lasttime = tim
    print("times")
    if(extime-tim < LAPSE):
        print(LAPSE -(extime-tim))
        #time.sleep((LAPSE -(extime-tim)))
    else:
        print("mucho tiempo")
        print(extime-tim)